import {
  AlipayCircleOutlined,
  LockOutlined,
  TaobaoCircleOutlined,
  UserOutlined,
  WeiboCircleOutlined,
} from '@ant-design/icons';
import {
  LoginForm,
  ProFormText,
} from '@ant-design/pro-components';
import {
  FormattedMessage,
  SelectLang,
  useIntl,
  useModel,
} from '@umijs/max';
import { Alert, App, Form, Checkbox, CheckboxChangeEvent } from 'antd';
import React, { useState, useRef, useEffect, ChangeEvent } from 'react';
import { flushSync } from 'react-dom';
import { history } from '@umijs/max';
import { login } from '@/services/ant-design-pro/api';
import CaptchaInput, { CaptchaInputRef } from '@/components/CaptchaInput';
import styles from './index.model.css';
import yupian from '@/images/gdfbgfbstrfbbv.png';
import { handleNumberInput } from '@/components/business/index';

const EXPIRATION_TIME = 24 * 60 * 60 * 1000; // 24小时的毫秒数

interface LoginMessageProps {
  content: string;
}

/**
 * 登录图标组件
 */
const ActionIcons: React.FC = () => {
  return (
    <>
      <AlipayCircleOutlined key="AlipayCircleOutlined" className={styles.action} />
      <TaobaoCircleOutlined key="TaobaoCircleOutlined" className={styles.action} />
      <WeiboCircleOutlined key="WeiboCircleOutlined" className={styles.action} />
    </>
  );
};

/**
 * 语言选择组件
 */
const Lang: React.FC = () => {
  return (
    <div className={styles.lang} data-lang>
      {SelectLang && <SelectLang />}
    </div>
  );
};

/**
 * 登录错误消息组件
 */
const LoginMessage: React.FC<LoginMessageProps> = ({ content }) => {
  return (
    <Alert
      style={{ marginBottom: 20 }}
      message={content}
      type="error"
      showIcon
    />
  );
};

/**
 * 登录页面组件
 */
const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>();
  const [type, setType] = useState<string>('admin');
  const [rememberPassword, setRememberPassword] = useState(false);
  const [captchaError, setCaptchaError] = useState('');

  const captchaRef = useRef<CaptchaInputRef>(null);
  const hasGetback = useRef(!!sessionStorage.getItem('getback'));

  const { initialState, setInitialState } = useModel('@@initialState');
  const { message } = App.useApp();
  const intl = useIntl();
  const [form] = Form.useForm();

  /**
   * 加载记住的密码信息
   */
  useEffect(() => {
    const loadRememberedCredentials = () => {
      try {
        const rememberedDataStr = localStorage.getItem('remember');
        if (rememberedDataStr) {
          const rememberedData = JSON.parse(rememberedDataStr);
          const { username, password, timestamp } = rememberedData;
          
          if (username && password && timestamp) {
            const currentTime = new Date().getTime();
            if (currentTime - timestamp < EXPIRATION_TIME) {
              form.setFieldsValue({
                username,
                password,
                autoLogin: false
              });
            } else {
              localStorage.removeItem('remember');
              form.setFieldsValue({ username });
            }
          }
        }
      } catch (error) {
        console.error('加载记住的登录信息失败：', error);
        localStorage.removeItem('remember');
      }
    };

    loadRememberedCredentials();
  }, [form]);

  /**
   * 限制浏览器返回按钮功能
   */
  useEffect(() => {
    let cleanupFns: (() => void)[] = [];
    
    if (hasGetback.current) {
      const clearHistoryStack = () => {
        const currentUrl = window.location.href;
        window.history.replaceState(null, document.title, currentUrl);
        window.history.pushState(null, document.title, currentUrl);
      };
      clearHistoryStack();

      const handlePopState = (e: PopStateEvent) => {
        e.preventDefault();
        e.stopPropagation();
        window.history.replaceState(null, document.title, window.location.href);
      };
      window.addEventListener('popstate', handlePopState, { capture: true });
      cleanupFns.push(() => window.removeEventListener('popstate', handlePopState, { capture: true }));

      const originalMethods = {
        pushState: history.pushState,
        replaceState: history.replaceState,
        go: history.go,
        back: history.back,
        forward: history.forward,
      };
      history.pushState = () => { };
      history.replaceState = () => { };
      history.go = () => { };
      history.back = () => { };
      history.forward = () => { };
      cleanupFns.push(() => Object.assign(history, originalMethods));

      const handleKeyDown = (e: KeyboardEvent) => {
        const target = e.target as HTMLElement;
        if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA') return;
        if (e.key === 'Backspace' || (e.altKey && e.key === 'ArrowLeft')) {
          e.preventDefault();
          e.stopPropagation();
        }
      };
      window.addEventListener('keydown', handleKeyDown, { capture: true });
      cleanupFns.push(() => window.removeEventListener('keydown', handleKeyDown, { capture: true }));
    }

    return () => {
      cleanupFns.forEach(fn => fn());
    };
  }, []);

  /**
   * 获取用户信息
   */
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({ ...s, currentUser: userInfo }));
      });
    }
  };

  /**
   * 处理登录提交
   */
  const handleSubmit = async (values: API.LoginParams & { captcha?: string }) => {
    try {
      // 验证码验证
      if (!captchaRef.current?.validateCaptcha(values.captcha)) {
        captchaRef.current?.refreshCaptcha();
        return;
      }

      const loginValues = {
        username: values.username,
        password: values.password,
      };
      
      const msg = (await login(loginValues)) as API.LoginResult & {
        code: number;
        msg: string;
        info: { id: string; username?: string };
        menu: any[];
        url: string;
        data: any;
      };

      if (msg.code === 1) {
        // 登录成功处理
        message.destroy();
        message.success(msg.msg || intl.formatMessage({
          id: 'pages.login.success',
          defaultMessage: '登录成功！',
        }));
        
        // 存储登录凭证
        sessionStorage.setItem('voucher', 'Login-credentials');
        sessionStorage.setItem('userinfo', JSON.stringify(msg.data));
        
        // 更新全局状态
        flushSync(() => {
          setInitialState((s) => ({
            ...s,
            currentUser: msg.data,
            lockScreenPassword: values.password,
            isLoggedIn: true,
            settings: { ...s?.settings, collapsed: false }
          }));
        });
        // 记住密码处理
        handleRememberPassword(values.username, values.password);
        // 获取用户信息
        await fetchUserInfo();
        // 登录成功跳转
        handleLoginSuccess();
        
      } else {
        // 登录失败处理
        setUserLoginState(msg);
        const loginFailureMessage = msg.msg || intl.formatMessage({
          id: 'pages.login.failure',
          defaultMessage: '登录失败，请重试！',
        });
        message.error(loginFailureMessage);
        captchaRef.current?.refreshCaptcha();
      }
    } catch (error) {
      // 异常处理
      const defaultLoginFailureMessage = intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '登录失败，请重试！',
      });
      console.log(error);
      message.error(defaultLoginFailureMessage);
      captchaRef.current?.refreshCaptcha();
    }
  };

  /**
   * 处理记住密码功能
   */
  const handleRememberPassword = (username: string, password: string) => {
    if (rememberPassword) {
      const rememberedData = {
        username,
        password,
        timestamp: new Date().getTime()
      };
      localStorage.setItem('remember', JSON.stringify(rememberedData));
    } else {
      localStorage.removeItem('remember');
    }
  };

  /**
   * 处理登录成功后的跳转（关键修复：清除残留锁屏状态）
   */
  const handleLoginSuccess = () => {
    const urlParams = new URL(window.location.href).searchParams;
    const redirectUrl = urlParams.get('redirect') || '/';
    
    // 清除可能残留的锁屏状态，确保新会话干净
    localStorage.removeItem('isLocked');
    // 清除解锁标记（防止异常状态干扰）
    sessionStorage.removeItem('isUnlocking');
    
    sessionStorage.removeItem('getback');
    hasGetback.current = false;
    
    setTimeout(() => {
      history.push(redirectUrl);
    }, 1000);
  };

  /**
   * 处理验证码验证成功
   */
  const handleCaptchaSuccess = () => {
    console.log('验证码验证成功');
    setCaptchaError('');
  };

  /**
   * 处理记住密码勾选状态变化
   */
  const handleRememberChange = (e: CheckboxChangeEvent) => {
    setRememberPassword(e.target.checked);
  };

  return (
    <div className={styles.contAiner}>
      {/* 图片区域 */}
      <div className={styles.imageSection}>
        <img src={yupian} alt="Login illustration" className={styles.loginImage} />
      </div>
      
      {/* 表单区域 */}
      <div className={styles.formContainer}>
        <div className={styles.lang}>
          <LoginForm
            form={form}
            title={null}
            initialValues={{ autoLogin: false }}
            onFinish={async (values) => {
              await handleSubmit(values as API.LoginParams & { captcha?: string });
            }}
            submitter={{
              searchConfig: { submitText: '登录' },
              render: (_, dom) => (
                <div className={styles.buttonContainer}>
                  <button type="submit" className={styles.submitButton}>登录</button>
                </div>
              ),
            }}
          >
            {/* 标签页 */}
            <div className={styles.customTabs}>
              <span>登录</span>
              <span>礼盒商城</span>
            </div>

            {/* 用户名输入框 */}
            <ProFormText
              name="username"
              fieldProps={{ 
                size: 'large', 
                prefix: <UserOutlined />,
              }}
              placeholder='账号'
              rules={[
                { required: true, message: <FormattedMessage id="pages.login.username.required" defaultMessage="请输入用户名!" /> },
                { min: 5, message: <FormattedMessage id="pages.login.username.minLength" defaultMessage="用户名至少5个字符!" /> },
                { max: 11, message: <FormattedMessage id="pages.login.username.maxLength" defaultMessage="用户名最多11个字符!" /> },
              ]}
            />

            {/* 密码输入框 */}
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined />,
                onChange: (e: ChangeEvent<HTMLInputElement>) => {
                  handleNumberInput(form, 'password', e, {
                    supportDecimal: false,
                    isSalaryRange: false,
                  });
                },
              }}
              placeholder="密码"
              rules={[
                { required: true, message: <FormattedMessage id="pages.login.password.required" defaultMessage="请输入密码！" /> },
                { min: 6, message: <FormattedMessage id="pages.login.password.minLength" defaultMessage="密码至少6个字符!" /> },
                { max: 18, message: <FormattedMessage id="pages.login.password.maxLength" defaultMessage="密码最多18个字符!" /> },
              ]}
            />

            {/* 验证码组件 */}
            <CaptchaInput
              ref={captchaRef}
              form={form}
              captchaError={captchaError}
              onCaptchaErrorChange={setCaptchaError}
              onCaptchaSuccess={handleCaptchaSuccess}
            />

            {/* 记住密码选项 */}
            <div className={styles.rememberWrapper}>
              <Checkbox
                checked={rememberPassword}
                onChange={handleRememberChange}
                className={styles.squareCheckbox}
              >
                记住密码
              </Checkbox>
            </div>
          </LoginForm>
        </div>
      </div>
    </div>
  );
};

export default Login;